import { PureComponent } from "react";
import { SearchBar,Carousel,Grid,Flex,TabBar,Button,PullToRefresh,ListView} from "antd-mobile"
import { ActivityIndicator } from 'antd-mobile';
import { connect } from 'dva';
import { Row, Col,Select } from 'antd';
import { handleImg, goToPage,isNull,handleOSS } from "../../utils/helper";
import {IntlProvider, addLocaleData,FormattedMessage} from 'react-intl';
import localeData from '../../../public/lang/data.json';
import 'antd/dist/antd.css'; // or 'antd/dist/antd.less'
import MToast from '../../components/Util/MToast';
const Option = Select.Option;
@connect(() => {
  return ({

  })
})
export default class MelaShop extends PureComponent{
  constructor(props){
    super(props);
    const dataSource = new ListView.DataSource({
      rowHasChanged: (row1, row2) => row1 !== row2 // rowHasChanged(prevRowData, nextRowData); 用其进行数据变更的比较
    })
    this.state = {
      carouselItem:[],
      loading:true,
      dataSource,
      datas:[],
      dataArr:[],
      currentPage: 0,
      pageSize: 20,
      hasMore: true,
      refreshing: true,
      isLoading: false,
      selectedTab: 'redTab',
      onImg:true,
      locale:'it',
      isOption:false,
    }
  }
  componentWillMount(){
    let {dispatch,location} = this.props;
this.bannerList();
 this.goodContent(true);
    if(localStorage.locale=='it'){
      this.setState({
        locale:'it',
        isOption:false
      })
    }else if(localStorage.locale=='zh'){
      this.setState({
        locale:'zh',
        isOption:true
      })
    }else{
      localStorage.setItem("locale",'it')
      this.setState({
        locale:'it',
        isOption:false
      })
    }

  }
  bannerList(){
    let {dispatch,location} = this.props;
    dispatch({
      type: "form/query",
      payload: {
        apiInfo: {
          url: "qry/all?_c=app_banner_list",
          params: [
          ],
          _c: "app_banner_list"
        },
        callback: (result) => {
          let { data } = result;
          this.setState({
            carouselItem:data,
            loading:false,

          })
          console.log(data)

        }
      }
    });
  };
  goodContent(ref = false){
    let {dispatch,location} = this.props;
    dispatch({
      type: "form/query",
      payload: {
        apiInfo: {
          url: "lv/data?_c=app_goods_page_list",
          params: [
            {
              key: "page_index",
              value: 1
            },
            {
              key: "page_size",
              value: 20
            },
          ],
          _c: "app_goods_page_list"
        },
        callback: (result) => {
          let { data } = result;
          console.log(data.list);
          console.log(data.list[0].store_id)
          localStorage.setItem("store_id",data.list[0].store_id)
          const len = data.list.length
          if (len <= 0) { // 判断是否已经没有数据了
            this.setState({
              refreshing: false,
              isLoading: false,
              hasMore: false
            })

            Toast.info('没有数据了~', 1)
            return false
          }
          if(len<this.state.pageSize){
            console.log("www")
            this.setState({
              hasMore: false
            })
          }else{
            console.log("rrr")
            this.setState({
              isLoading: false,
              hasMore: true
            })
          }
          // this.setState({
          //   dataSource: this.state.dataSource.cloneWithRows(data),
          //   dataSource:data,
          //   loading:false,
          //
          // })
          if (ref) {
            //这里表示刷新使用
            // 下拉刷新的情况，重新添加数据即可(这里等于只直接用了第一页的数据)
            this.setState({
              pageNo: this.state.pageNo,
              dataSource: this.state.dataSource.cloneWithRows(data.list), // 数据源中的数据本身是不可修改的,要更新datasource中的数据，请（每次都重新）调用cloneWithRows方法
              hasMore: true, // 下拉刷新后，重新允许开下拉加载
              refreshing: false, // 是否在刷新数据
              isLoading: false, // 是否在加载中
              dataArr: data.list // 保存数据进state，在下拉加载时需要使用已有数据
            })
          } else {
            // 这里表示上拉加载更多
            // 合并state中已有的数据和新增的数据
            var dataArr = this.state.dataArr.concat(data.list) //关键代码
            this.setState({
              pageNo: this.state.pageNo,
              dataSource: this.state.dataSource.cloneWithRows(dataArr), // 数据源中的数据本身是不可修改的,要更新datasource中的数据，请（每次都重新）调用cloneWithRows方法
              refreshing: false,
              isLoading: false,
              hasMore: false,
              dataArr: dataArr // 保存新数据进state
            })
          }
        }
      }
    });
  }
  // 滑动到底部时加载更多
  onEndReached = (event) => {
    console.log(this.state.dataArr)
    if(this.state.dataArr.length/20<1){
      this.setState({
        isLoading: false
      })
      console.log("ffffffffffff")
      return
    }else{
      this.setState({
        isLoading: true,
        pageNo: this.state.pageNo + 1, // 加载下一页
      }, ()=> {
        this.goodContent(false)
      })

    }
    // console.log("wwwwwwwwwwwwwwwwwwwwwwwwwwwwww")
    // console.log(this.state.isLoading)
    // // 加载中或没有数据了都不再加载
    // if (this.state.isLoading || !this.state.hasMore) {
    //   console.log("dddddd")
    //   return
    // }

  }
  goodList() {
    let { dataSource} = this.state;

    if (!dataSource || dataSource.length == 0) {
      return (
        <div style={{ padding: "40px 0", textAlign: "center", fontSize: "20px", color: "#555" }}>
          {T(localeData[localStorage.locale].goodsDetailCartNoGood)}
        </div>
      )
    }
    else {
      let contents = [];
      return (
        <div className="box" style={{height:'100%',paddingBottom:'20%'}}>
          {dataSource.map((i,k) => (
            <div  key={k} style={{background:'#fff',fontWeight:'bold',padding:'5% 5% 5%',borderRadius:'10px'}} className="item">
              <div onClick={(e)=>{this.handleDetail(e,i)}}>
                <img src={handleOSS(i.img_url)} style={{width:'100%',height:'100%'}}/>
              </div>
              <div style={{overflow:'hidden',margin:'10% 0px 0px'}}>
                <p className="ellipsis2" style={{margin:'12px 0px 0px',textAlign:'left',color:'#595867',fontSize:'13px',}}>{i.goods_name}</p>
                <div style={{overflow:'hidden',marginTop:'8px'}}>
                  <div style={{float:'left',color:'#F09600',fontSize:'15px',marginTop:'5px'}}>€{i.price}</div>
                  <div style={{float:'right',width:'34px',height:'34px'}} onClick={(e) => {this.handleAdd(e,i) }}>
                    <img src="image/cart1.png" style={{width:'32px',height:'32px'}}/>
                  </div>
                </div>

              </div>

              {/*<Button type="primary" size="small" inline style={{marginBottom:'1em'}} onClick={(e) => {this.handleAdd(e,i) }}>+ADD</Button>*/}
            </div>

          ))}
        </div>

      )
    }
  }
  handleDetail=(e,i)=>{
    let {dispatch} = this.props;
    goToPage({ dispatch, config: { url: "/goodsDetail?id="+i.id+"&store_id="+i.store_id }, isReplace: false })
  }
  handleAdd=(e,i)=>{
    // console.log(i);
    let {dispatch} = this.props;
    dispatch({
      type: "form/query",
      payload: {
        apiInfo: {
          url: "cart/add",
          params: [
            {
              key: "goods_id",
              value: i.id
            },
            {
              key: "goods_name",
                value: i.goods_name
            },
            {
              key: "img_url",
                value: i.img_url
            },
            {
              key: "price",
                value: i.price
            },
            {
              key: "quantity",
                value: 1
            }
          ]
        },
        callback: (result) => {
          let { data } = result;
       console.log(data)
            MToast.info(T(localeData[localStorage.locale].goodsDetailCartInfo,3, null, false));

        }
      }
    })
  }
  chooseLocale=(value)=>{
    const {locale}=this.state;
    // // const localeValue = value;
    localStorage.setItem("locale",value)
    this.setState({
      locale: value,
      onImg:false
    });
    console.log(value);
  }
  onRefresh=()=>{
    this.bannerList();
    this.goodContent(true);
  }

  render(){
    let {dispatch} = this.props;
    let {carouselItem,dataSource,dataSourceObj,loading,onImg,isOption} = this.state;
    const messages = localeData[localStorage.locale]
    console.log(this.state.locale,isOption)
    const row =(rowData, sectionID, rowID)=>{
      console.log(rowData)
      return (
        <div style={{marginBottom:'6%'}}>
            <div  key={rowID} style={{background:'#fff',fontWeight:'bold',padding:'5% 5% 5%',borderRadius:'10px'}} className="item">
              <div onClick={(e)=>{this.handleDetail(e,rowData)}}>
                <img src={handleOSS(rowData.img_url)} style={{width:'100%',height:'100%'}}/>
              </div>
              <div style={{overflow:'hidden',margin:'10% 0px 0px'}}>
                <p className="ellipsis2" style={{margin:'12px 0px 0px',textAlign:'left',color:'#595867',fontSize:'13px',}}>{rowData.goods_name}</p>
                <div style={{overflow:'hidden',marginTop:'8px'}}>
                  <div style={{float:'left',color:'#F09600',fontSize:'15px',marginTop:'5px'}}>€{rowData.price}</div>
                  <div style={{float:'right',width:'34px',height:'34px'}} onClick={(e) => {this.handleAdd(e,rowData) }}>
                    <img src="image/cart1.png" style={{width:'32px',height:'32px'}}/>
                  </div>
                </div>

              </div>

              {/*<Button type="primary" size="small" inline style={{marginBottom:'1em'}} onClick={(e) => {this.handleAdd(e,i) }}>+ADD</Button>*/}
            </div>


        </div>

      )
    }
    if (loading) {
      return (
        <div className="normal">
          <ActivityIndicator toast text="正在加载" animating={true} />
        </div>
      )
    }
    return(
      <div style={{background:'rgb(249, 247, 247)'}}>
        <IntlProvider
          locale={ this.state.locale } messages={messages}
        >
          <div>
            {isOption?
              <div >
                {/*{onImg?<img src="image/china.png" style={{position:'fixed',top:'3%',left:'2%',zIndex:'100',width:'16px',height:'16px'}}/>:''}*/}
                <Select
                defaultValue="zh"
                onChange={this.chooseLocale}
                bordered={false}
                style={{position:'fixed',top:'3%',left:'4%',zIndex:'200',width:'20%',}}
              >
                {/*<Option key="cn" value="en">English</Option>*/}
                <Option  key="it" value="it">
                  <div className="demo-option-label-item" style={{fontSize:'12px'}}>
                  <span role="img" aria-label="IT">
                    <img src="image/Italy.png" style={{width:'16px',height:'16px',marginRight:'3px'}}/>
                  </span>
                    IT
                  </div>
                </Option>
                <Option  key="en" value="zh" >
                  <div className="demo-option-label-item" style={{fontSize:'12px'}}>
                  <span role="img" aria-label="ZH">
                    <img src="image/china.png" style={{width:'16px',height:'16px',marginRight:'3px'}}/>
                  </span>
                    CN
                  </div>
                </Option>

              </Select>
              </div>:
              <div>
                {/*{onImg?<img src="image/Italy.png" style={{position:'fixed',top:'3%',left:'2%',zIndex:'100',width:'16px',height:'16px'}}/>:""}*/}
                <Select
                  defaultValue="it"
                  onChange={this.chooseLocale}
                  bordered={false}
                  style={{position:'fixed',top:'3%',left:'4%',zIndex:'200',width:'20%',}}
                >
                  {/*<Option key="cn" value="en">English</Option>*/}
                  <Option  key="it" value="it">
                    <div className="demo-option-label-item" style={{fontSize:'12px'}}>
                  <span role="img" aria-label="IT">
                    <img src="image/Italy.png" style={{width:'16px',height:'16px',marginRight:'3px'}}/>
                  </span>
                      IT
                    </div>
                  </Option>
                  <Option  key="en" value="zh" >
                    <div className="demo-option-label-item" style={{fontSize:'12px'}}>
                  <span role="img" aria-label="ZH">
                    <img src="image/china.png" style={{width:'16px',height:'16px',marginRight:'3px'}}/>
                  </span>
                      CN
                    </div>
                  </Option>

                </Select>
              </div>
            }


          <div maxLength={8} style={{position:'fixed',top:'2%',left:'3%',width:'92%',zIndex:'100',height:'44px',border:'1px solid #ddd',borderRadius:'15px',background:"#fff"}} onClick={()=>{goToPage({ dispatch, config: { url: "/searchPage" }, isReplace: false })}}>
            <div style={{position:'absolute',top:'25%',left:'37%'}}>
              <img src="image/search_24px.png" style={{width:'24px',height:'24px'}}/><span style={{color:'#C9C9C9',fontSize:'13px'}}>{messages.searchPlaceholder}</span>
            </div>
          </div>
          </div>
          <PullToRefresh
            damping={100}
            onRefresh={this.onRefresh}
          >
          <Carousel
            autoplay={true}
            infinite
            autoplayInterval={10000}
            speed={400}
          >
            {this.state.carouselItem.map((i,k) => (
              <a
                key={k}
                style={{ display: 'inline-block', width: '100%', height: this.state.imgHeight }}
              >
                <img
                  src={handleOSS(i.url)}
                  alt=""
                  style={{ width: '100%', verticalAlign: 'top',height:'237px' }}
                  onLoad={() => {
                    // fire window resize event to change height
                    this.setState({ imgHeight: '237px' });
                  }}
                />
              </a>
            ))}
          </Carousel>
          <p style={{color:'#2E2D35',fontSize:'17px',margin:'16px 16px 0px'}}>Più venduti</p>
            <ListView
              ref={el => this.lv = el}
              dataSource={this.state.dataSource}
              renderRow={row}
              useBodyScroll
              onEndReachedThreshold={10}
              onEndReached={this.onEndReached}
              pageSize={5}
              scrollEventThrottle={1}
              renderFooter={() => (<div className="footer">{this.state.isLoading ? '加载中...' : '暂无更多数据'}</div>)}
             // className="box"
              style={{
                height:'100%',
                paddingBottom:'20%',
              }}
            >

            </ListView>
          {/*{this.goodList()}*/}
          </PullToRefresh>
          <div style={{position:'fixed',bottom:'0px',left:'0px',width:'100%'}}>
            <TabBar
              unselectedTintColor="#949494"
              tintColor="#F09600"
              barTintColor="white"
              hidden={this.state.hidden}
            >
              <TabBar.Item
                title={messages.home}
                key="Life"
                icon={<div style={{
                  width: '24px',
                  height: '24px',
                  background: 'url(image/home2.png) center center /  21px 21px no-repeat' }}
                />
                }
                selectedIcon={<div style={{
                  width: '24px',
                  height: '24px',
                  background: 'url(image/home3.png) center center /  21px 21px no-repeat' }}
                />
                }
                selected={this.state.selectedTab === 'redTab'}
                onPress={() => {
                  this.setState({
                    selectedTab: 'redTab',
                  });
                  goToPage({ dispatch, config: { url: "/shop_home" }, isReplace: false })
                }}
                data-seed="logId"
              >

              </TabBar.Item>
              <TabBar.Item
                icon={
                  <div style={{
                    width: '24px',
                    height: '24px',
                    background: 'url(image/category.png) center center /  21px 21px no-repeat' }}
                  />
                }
                selectedIcon={
                  <div style={{
                    width: '24px',
                    height: '24px',
                    background: 'url(image/category1.png) center center /  21px 21px no-repeat' }}
                  />
                }
                title={messages.category}
                key="Koubei"

                selected={this.state.selectedTab === 'blueTab'}
                onPress={() => {
                  this.setState({
                    selectedTab: 'blueTab',
                  });
                  goToPage({ dispatch, config: { url: "/category" }, isReplace: false })
                }}
                data-seed="logId1"
              >

              </TabBar.Item>
              <TabBar.Item
                icon={
                  <div style={{
                    width: '24px',
                    height: '24px',
                    background: 'url(image/cart4.png) center center /  21px 21px no-repeat' }}
                  />
                }
                selectedIcon={
                  <div style={{
                    width: '24px',
                    height: '24px',
                    background: 'url(image/cart5.png) center center /  21px 21px no-repeat' }}
                  />
                }
                title={messages.cart}
                key="Friend"
                selected={this.state.selectedTab === 'greenTab'}
                onPress={() => {
                  this.setState({
                    selectedTab: 'greenTab',
                  });
                  goToPage({ dispatch, config: { url: "/goodcart" }, isReplace: false })
                }}
              >
              </TabBar.Item>
              <TabBar.Item
                icon={{ uri: 'image/my.png' }}
                selectedIcon={{ uri: 'image/my1.png' }}
                title={messages.my}
                key="my"
                selected={this.state.selectedTab === 'yellowTab'}
                onPress={() => {
                  this.setState({
                    selectedTab: 'yellowTab',
                  });
                  goToPage({ dispatch, config: { url: "/my" }, isReplace: false })
                }}
              >
              </TabBar.Item>
            </TabBar></div>
        </IntlProvider>


      </div>
    )
  }
}
